package longrise.phone.com.bjjt_henan.main;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mobstat.StatService;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.listview_library_refrush.PullToRefreshBase;
import com.longrise.android.listview_library_refrush.PullToRefreshListView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Adapter.MyCollectAdapter;
import longrise.phone.com.bjjt_henan.Constant.MsgConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.BDLocationManager;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;
import longrise.phone.com.bjjt_henan.bindinginformation.BindCarView;
import longrise.phone.com.bjjt_henan.bindinginformation.MyCollectView;
import longrise.phone.com.bjjt_henan.widget.DealDialog;
import longrise.phone.com.bjjt_henan.widget.WeacherDialog;

/**
 * 车生活
 * Created by Administrator on 2017/5/10.
 */

public class CarDailyView extends LFView implements BDLocationListener, View.OnClickListener,
        ILSMsgListener, AdapterView.OnItemClickListener {

    private Context mContext;

    private View mView;

    private EntityBean entityBean;

    private TextView weatherTV;

    private TextView tempTV;

    private TextView washercarTV;

    private BDLocationManager manager;

    private BaseApplication mApplication;

    private LinearLayout peccancyLLayout;

    private LinearLayout inspectLLayout;

    private LinearLayout chargeLLayout;

    private LinearLayout carassessLLayout;

    private ImageView accnotifyIV;

    private DealDialog dealDialog;

    private TextView moreTV;

    private MyCollectAdapter newsAdapter;

    private EntityBean[] newsBean;

    private LinearLayout weacherLayout;

    private WeacherDialog weacherDialog;

    private EntityBean weacherBean;

    private PullToRefreshListView mListView;

    private boolean isLoading = false;// 正在刷新

    private int bindState;//绑定状态

    private Dialog assessDialog;

    private LinearLayout snapshotLLayout;

    private LinearLayout pvoiceLLayout;

    public CarDailyView(Context context) {
        super(context);
        this.mContext = context;
        this.mApplication = ((MainActivity) context).getAppData();
    }

    public CarDailyView(Context context, EntityBean bean) {
        this(context);
        this.entityBean = bean;
    }

    public void setEntityBean(EntityBean entityBean) {
        this.entityBean = entityBean;
    }

    public void setBindState(int bindState) {
        this.bindState = bindState;
    }

    @Override
    public View getView() {
        return mView;
    }

    @Override
    public void init() {
        mView = LayoutInflater.from(mContext).inflate(R.layout.view_cardaily_main, null);
        if (mView == null) {
            return;
        }
        mListView = (PullToRefreshListView) mView.findViewById(R.id.cardaily_plv_news);
        View headView = LayoutInflater.from(mContext).inflate(R.layout.view_cardaily, null);
        mListView.getRefreshableView().addHeaderView(headView);
        initRefreshView();
        //头部内容
        tempTV = (TextView) headView.findViewById(R.id.cardaily_tv_temp);
        weatherTV = (TextView) headView.findViewById(R.id.cardaily_tv_weather);
        weacherLayout = (LinearLayout) headView.findViewById(R.id.cardaily_ll_weather);
        washercarTV = (TextView) headView.findViewById(R.id.cardaily_tv_carinfo);
        accnotifyIV = (ImageView) headView.findViewById(R.id.cardaily_iv_accnotify);
        peccancyLLayout = (LinearLayout) headView.findViewById(R.id.cardaily_ll_peccancy);
        inspectLLayout = (LinearLayout) headView.findViewById(R.id.cardaily_ll_carinspect);
        chargeLLayout = (LinearLayout) headView.findViewById(R.id.cardaily_ll_charge);
        carassessLLayout = (LinearLayout) headView.findViewById(R.id.cardaily_ll_carassess);
        snapshotLLayout = (LinearLayout) headView.findViewById(R.id.cardaily_ll_snapshot);
        pvoiceLLayout = (LinearLayout) headView.findViewById(R.id.cardaily_ll_policevoice);
        moreTV = (TextView) headView.findViewById(R.id.cardaily_tv_morenews);

        newsAdapter = new MyCollectAdapter(mContext);
        mListView.setAdapter(newsAdapter);

        addILSMsgListener(this);
        setEvent(true);
        setIViewSize();
    }

    private void initRefreshView() {
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        // 刚拉时的提示
        mListView.getLoadingLayoutProxy().setPullLabel("加载列表数据...");
        // 正在刷新提示
        mListView.getLoadingLayoutProxy().setRefreshingLabel("正在载入...");
        // 拉倒一定高度的提示
        mListView.getLoadingLayoutProxy().setReleaseLabel("放开以刷新...");
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!isLoading) {
                    if (null != manager) {
                        manager.bdLocation();
                    }
                    loadCarNews();
                    isLoading = true;
                }
            }
        });
    }

    //设置导航项统一的图片宽高
    private void setIViewSize() {
        Drawable kDrawable = ContextCompat.getDrawable(mContext, R.mipmap.icon_peccancy_new);
        int width = kDrawable.getIntrinsicWidth();
        int height = kDrawable.getIntrinsicHeight();

        ImageView pvIV = (ImageView) mView.findViewById(R.id.cardaily_iv_policevoice);
        pvIV.setLayoutParams(new LinearLayout.LayoutParams(width, height));
        pvIV.setBackgroundResource(R.mipmap.icon_policevoice);
    }

    private void setEvent(boolean flag) {
        if (null != accnotifyIV) {
            accnotifyIV.setOnClickListener(flag ? this : null);
        }
        if (null != peccancyLLayout) {
            peccancyLLayout.setOnClickListener(flag ? this : null);
        }
        if (null != inspectLLayout) {
            inspectLLayout.setOnClickListener(flag ? this : null);
        }
        if (null != chargeLLayout) {
            chargeLLayout.setOnClickListener(flag ? this : null);
        }
        if (null != moreTV) {
            moreTV.setOnClickListener(flag ? this : null);
        }
        if (null != mListView) {
            mListView.setOnItemClickListener(flag ? this : null);
        }
        if (null != weacherLayout) {
            weacherLayout.setOnClickListener(flag ? this : null);
        }
        if (null != carassessLLayout) {
            carassessLLayout.setOnClickListener(flag ? this : null);
        }
        if (null != snapshotLLayout) {
            snapshotLLayout.setOnClickListener(flag ? this : null);
        }
        if (null != pvoiceLLayout) {
            pvoiceLLayout.setOnClickListener(flag ? this : null);
        }
    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public void refresh() {
        getLocation();
        DialogUtils.showDialog(mContext);
        loadCarNews();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (newsBean == null) {
            return;
        }
        if (position < 2) {
            return;
        }
        EntityBean bean = newsBean[position - 2];
        Intent cintent = new Intent(mContext, CarNewsActivity.class);
        cintent.putExtra("databean", bean);
        mContext.startActivity(cintent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cardaily_iv_accnotify://周边事故示警
                //判断是否有定位权限
                if (!PermissionHelper.checkLocPermissions(mContext)) {
                    return;
                }
                StatService.onEvent(mContext, "accident_notify", "周边事故警示");
                TravelServiceView baidumapview = new TravelServiceView(mContext, 2);
                FrameworkManager.getInstance().showNewForm(mContext, baidumapview);
                break;
            case R.id.cardaily_ll_peccancy://违章
                StatService.onEvent(mContext, "peccancy_search", "违章查询");
                checkCarInfo(0);
                break;
            case R.id.cardaily_ll_carinspect://年检
                StatService.onEvent(mContext, "inspect_notify", "年检提醒");
                checkCarInfo(1);
                break;
            case R.id.cardaily_ll_charge://充电站
                //判断是否有定位权限
                if (!PermissionHelper.checkLocPermissions(mContext)) {
                    return;
                }
                StatService.onEvent(mContext, "charge_station", "充电站");
                TravelServiceView mapview = new TravelServiceView(mContext, 3);
                FrameworkManager.getInstance().showNewForm(mContext, mapview);
                break;
            case R.id.cardaily_tv_morenews:
                StatService.onEvent(mContext, "more_news", "车主头条");
                MyCollectView newsView = new MyCollectView(mContext);
                newsView.setType(1);
                FrameworkManager.getInstance().showNewForm(mContext, newsView);
                break;
            case R.id.cardaily_ll_weather:
                showWeaDialog();
                break;
            case R.id.cardaily_ll_carassess:
                boolean flag = PrefUtils.getBoolean(mContext, "carassess", false);
                if (flag) {//已经显示过
                    Intent cintent = new Intent(mContext, UserGuideActivity.class);
                    cintent.putExtra("title", mContext.getString(R.string.car_assess));
                    cintent.putExtra("url", UserGuideActivity.CAR_ASSESS);
                    mContext.startActivity(cintent);
                } else {
                    showAssessDialog();
                    PrefUtils.setBoolean(mContext, "carassess", true);
                }
                break;
            case R.id.cardaily_ll_snapshot:
                PeccancySelectView slectView = new PeccancySelectView(mContext);
                FrameworkManager.getInstance().showNewForm(mContext, slectView);
                break;
            case R.id.cardaily_ll_policevoice:
                savePCInfo();
                Intent cintent = new Intent(mContext, UserGuideActivity.class);
                cintent.putExtra("title", mContext.getString(R.string.police_radio));
                cintent.putExtra("url", UserGuideActivity.POLICE_RADIO);
                mContext.startActivity(cintent);
                break;
            default:
                break;
        }
    }

    //记录警广之声调用的信息
    private void savePCInfo() {
        String userflag = mApplication.getKckpName();
        String token = mApplication.getToken();
        ApiImpI.getInstance(mContext).savePVInfo(userflag, token, null);
    }

    //爱车估价操作的提示框
    private void showAssessDialog() {
        if (assessDialog == null) {
            assessDialog = new Dialog(mContext, R.style.AlertDialogStyle);
            View view = View.inflate(mContext, R.layout.dialog_inspect_notification, null);
            TextView titleTV = (TextView) view.findViewById(R.id.dialog_tv_title);
            TextView carnoTV = (TextView) view.findViewById(R.id.dialog_tv_carno);
            view.findViewById(R.id.dialog_tv_info).setVisibility(View.GONE);
            titleTV.setText(mContext.getResources().getString(R.string.insurance_wait));
            carnoTV.setText(mContext.getResources().getString(R.string.carassess_detail));
            view.findViewById(R.id.dialog_btn_confirm).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    assessDialog.dismiss();
                    Intent cintent = new Intent(mContext, UserGuideActivity.class);
                    cintent.putExtra("title", mContext.getString(R.string.car_assess));
                    cintent.putExtra("url", UserGuideActivity.CAR_ASSESS);
                    mContext.startActivity(cintent);
                }
            });
            assessDialog.setContentView(view);
            Window dialogWindow = assessDialog.getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            DisplayMetrics d = mContext.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
            lp.width = (int) (d.widthPixels * 0.85);
            dialogWindow.setAttributes(lp);
        }
        assessDialog.show();
    }

    //显示未来三天的天气
    private void showWeaDialog() {
        if (weacherBean == null) {
            return;
        }
        if (null == weacherDialog) {
            weacherDialog = new WeacherDialog(mContext);
        }
        weacherDialog.setData(weacherBean);
        weacherDialog.show();
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        if (null == mView) {
            return;
        }
        if (null != location) {
            String cityCode = location.getCityCode();
            if (!StringUtils.isEmpty(cityCode)) {
                String cityName = location.getCity();
                mApplication.setCityName(cityName);
                String latitude = String.valueOf(location.getLatitude());
                String longitude = String.valueOf(location.getLongitude());
                //获取天气
                loadWeather(longitude, latitude);

                if (manager != null) {
                    manager.ondestroty();
                    manager = null;
                }
            }
        }
    }

    @Override
    public Object onLSMsg(int i, Object... objects) {
        if (i == MsgConstant.PERMISSION) {
            if (objects != null && objects.length > 0 && "PERMISSION_GRANTED".equals(objects[0])) {
                getLocation();
                return false;
            }
        }
        return null;
    }

    private void getLocation() {
        //判断是否有定位权限
        if (!PermissionHelper.checkLocPermissions(mContext)) {
            return;
        }
        if (manager == null) {
            manager = new BDLocationManager(mContext);
            manager.setLocationListener(this);
        }
        manager.startLocation();
    }

    //加载天气
    private void loadWeather(String lon, String lat) {
        String userflag = mApplication.getKckpName();
        String token = mApplication.getToken();
        ApiImpI.getInstance(mContext).getWeather(lon, lat, userflag, token, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {

            }

            @Override
            public void onSuccess(Object result) {
                if (mView == null) {
                    return;
                }
                if (result != null) {
                    EntityBean weaBean = (EntityBean) result;
                    String restate = weaBean.getString("restate");
                    if (TextUtils.equals(restate, "1")) {
                        weacherBean = weaBean.getBean("data");
                        if (null != weacherBean) {
                            EntityBean wash = weacherBean.getBean("washcar");
                            if (null != wash) {
                                String value = wash.getString("zs");
                                washercarTV.setText(value + "洗车");
                            }
                            EntityBean[] weather = weacherBean.getBeans("weather");
                            if (null != weather && weather.length > 0) {
                                String temp = weather[0].getString("temperature");
                                tempTV.setText(WeacherDialog.getWeacherStr(temp));
                                String type = weather[0].getString("weather");
                                weatherTV.setText(type);
                            }
                        }
                    }
                }
            }
        });
    }

    //加载车主头条（默认加载5条）
    private void loadCarNews() {
        String userflag = mApplication.getKckpName();
        String token = mApplication.getToken();
        ApiImpI.getInstance(mContext).searchMoreNews(userflag, token, "2", null, "5", new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
                isLoading = false;
                if (null != mListView) {// 停止刷新
                    mListView.onRefreshComplete();
                }
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(mContext, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                isLoading = false;
                DialogUtils.closeDialog();
                if (mView == null) {
                    return;
                }
                if (null != mListView) {// 停止刷新
                    mListView.onRefreshComplete();
                }
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals(restate, "1")) {
                    EntityBean[] beans = bean.getBeans("data");
                    if (beans != null && beans.length > 0) {
                        newsBean = beans;
                        newsAdapter.setData(newsBean);
                        newsAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private void checkCarInfo(int type) {
        if (bindState == -1) {
            UiUtil.showToast(mContext, "数据加载有误,请稍后重试！");
            LSMsgCall(99, "bindinfo");
            return;
        }
        EntityBean[] cars = null;
        if (entityBean != null) {
            cars = entityBean.getBeans("car");
        }
        if (null == cars || cars.length < 1) {//未绑定车辆
            if (dealDialog == null) {
                dealDialog = new DealDialog(mContext);
                dealDialog.setInfo(R.string.bind_car);
                dealDialog.setCancel("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dealDialog.dismiss();
                    }
                });
                dealDialog.setConfirm("绑定车辆", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dealDialog.dismiss();
                        BindCarView bindcarview = new BindCarView(mContext, null);
                        FrameworkManager.getInstance().showNewForm(mContext, bindcarview);
                    }
                });
            }
            dealDialog.show();
            return;
        }
        SelectCarView carView = new SelectCarView(mContext, cars);
        carView.setType(type);
        FrameworkManager.getInstance().showNewForm(mContext, carView);
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        mView = null;
        setEvent(false);
        removeILSMsgListener(this);
        if (manager != null) {
            manager.ondestroty();
            manager = null;
        }
        if (null != dealDialog) {
            dealDialog.dismiss();
            dealDialog = null;
        }
        if (null != weacherDialog) {
            weacherDialog.dismiss();
            weacherDialog = null;
        }
        if (null != assessDialog) {
            assessDialog.dismiss();
            assessDialog = null;
        }
        if (null != mListView) {
            mListView.setAdapter(null);
            mListView = null;
        }
    }
}
